<?php
/**
 * Class Wechat
 * Desc 公众号
 * Create on 2021/10/20 17:19
 * Create by wangyafang
 */

namespace app\api\controller\xyb;


use app\admin\model\xyb\system\Config;
use app\api\model\xyb\WechatOfficialAccount;
use Exception;

class Wx extends Base
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $wxtoken = '';

    public function _initialize(){
        $this->wxtoken  = (new Config())->where('id',1)->value('xyb_configuration');
        if(isset($_GET['echostr']) && !empty($_GET['echostr'])) {
            if($this->checkSignature()){
                $echoStr = $_GET["echostr"];
                echo $echoStr;
                exit;
            }
        } else {
            $this->index();
        }
    }


    /*
     * desc:处理微信是否关注/取消事件
     * */
    public function index()
    {
        $wechatOfficialAccountModel = new WechatOfficialAccount();
        $wechatController = new Wechat();
        $access_token = $wechatController->_getAccessToken();
        $param = $this->request->param();
        $curl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$param['openid']."&lang=zh_CN";
        $content = $this->_request($curl);
        $data = json_decode($content,true);
        if(isset($data['errcode']) && $data['errcode'] == 40001) {
            $access_token = $wechatController->_getAccessToken();
            $curl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$param['openid']."&lang=zh_CN";
            $content = $this->_request($curl);
            $data = json_decode($content,true);
        }
        if($data['subscribe'] == 0) {
            WechatOfficialAccount::destroy(['openid'=>$param['openid']]);
        } else {
            $query = $wechatOfficialAccountModel->where('openid',$param['openid'])->find();
            if($query) {
                $wechatOfficialAccountModel->allowField(true)->save($data,['openid' => $param['openid']]);
            } else {
                $data['openid'] = $param['openid'];
                $wechatOfficialAccountModel->allowField(true)->save($data);
            }
        }
        echo "success";
        return;
    }

    private function _request($curl,$https=true,$method='GET',$data=null){
        // 创建一个新cURL资源
        $ch = curl_init();

        // 设置URL和相应的选项
        curl_setopt($ch, CURLOPT_URL, $curl);  //要访问的网站
        //启用时会将头文件的信息作为数据流输出。
        curl_setopt($ch, CURLOPT_HEADER, false);
        //将curl_exec()获取的信息以字符串返回，而不是直接输出。
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        if($https){
            //FALSE 禁止 cURL 验证对等证书（peer's certificate）。
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); //验证主机
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        }
        if($method == 'POST'){
            curl_setopt($ch, CURLOPT_POST, true); //发送 POST 请求
            //全部数据使用HTTP协议中的 "POST" 操作来发送。
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }


        // 抓取URL并把它传递给浏览器
        $content = curl_exec($ch);

        //关闭cURL资源，并且释放系统资源
        curl_close($ch);

        return $content;
    }

    public function valid()
    {
        $echoStr = $_GET["echostr"];

        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }

    private function checkSignature()
    {
        if (!$this->wxtoken) {
            throw new Exception('TOKEN is not defined!');
        }

        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = $this->wxtoken;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }
}